package com.twu.biblioteca;

public class LogIn {

    private static final String[] requests = {"Log in? (y/n): ", "Username: ", "Password: "};
    UserInputHandler userInputHandler;
    CustomerCollection customerCollection;

    public LogIn(CustomerCollection customerCollection) {
        this.customerCollection = customerCollection;
        userInputHandler = new UserInputHandler(System.in);
    }

    public Customer requestAndAttemptLogIn() {
        Customer customer = askForCustomerViaUsername();
        if(customer != null && customer.passwordEquals(askForPassword())) {
            return customer;
        }
        else {
          System.out.print("Invalid Password\n");
          return null;
        }
    }
    private Customer askForCustomerViaUsername() {
        printRequest(1);
        try {
            return customerCollection.getCustomer(userInputHandler.readUsernameRequest());
        }
        catch (Exception error) {
            System.out.print("Invalid Username\n");
            return null;
        }
    }

    private String askForPassword() {
        printRequest(2);
        try {
            return userInputHandler.readPasswordRequest();
        }
        catch (Exception error) {
            return null;
        }
    }

    public void printRequest(int i) {
        System.out.print(requests[i]);
    }
}
